package misty.mispic.app.comp

import com.sun.javafx.tk.Toolkit
import groovy.transform.CompileStatic
import javafx.application.Platform
import javafx.collections.ObservableList
import javafx.scene.control.TreeItem

import java.nio.file.FileSystem
import java.nio.file.Files
import java.nio.file.Path

/**
 * Created by Misty on 2015/1/24.
 */
@CompileStatic
class FileTreeItem extends TreeItem {
    private boolean isFirstTimeChildren = true
    private boolean isFirstTimeLeaf = true
    private boolean isLeaf

    FileTreeItem(it) {
        setValue(it)
    }

    @Override
    public boolean isLeaf() {
        if (isFirstTimeLeaf) {
            isFirstTimeLeaf = false;
            if (value instanceof FileSystem) {
                isLeaf = false
            } else if (value instanceof Path) {
                isLeaf = !(Files.isDirectory(value) && Files.isReadable(value))
            } else {
                isLeaf = false
            }
        }
        return isLeaf
    }


    @Override
    public ObservableList<TreeItem> getChildren() {
        if (isFirstTimeChildren) {
            isFirstTimeChildren = false

            // First getChildren() call, so we actually go off and
            // determine the children of the File contained in this TreeItem.
            buildChildren()
        }
        return super.getChildren()
    }

    private void buildChildren() {
        Toolkit.toolkit.checkFxUserThread()
        if (value instanceof FileSystem) {
            (value as FileSystem).rootDirectories.each {
                super.getChildren() << new FileTreeItem(it)
            }
        } else if (value instanceof Path) {
            new Thread({ // TODO. ThreadPool is better. by Misty
                println(Thread.currentThread())
                def res = []
                (value as Path).eachDir { Path p ->
                    if (Files.isReadable(p)) {
                        res << new FileTreeItem(p)
                    }
                }
                Platform.runLater {
                    super.children.setAll(res)
                }
            }).start()
        } else {
            super.children.clear()
        }
    }
}
